// 点击试卷后的缩略信息
<template>
  <div class="container">
   <div id="msg">
    <div class="title">
      <span>试卷列表</span>
      <span>/  {{examData.source}}</span>
    </div>
    <div class="wrapper">
      <ul class="top">
        <li class="example">{{examData.source}}</li>
        <li><i class="iconfont icon-pen-"></i></li>
        <li><i class="iconfont icon-share"></i></li>
        <li class="right">
          <div>
            <span class="count">总分</span>
            <span class="score">{{score[0]+score[1]+score[2]}}</span>
          </div>
        </li>
      </ul>
      <ul class="bottom">
        <li>更新于{{examData.examDate}}</li>
        <li>来自 {{examData.institute}}</li>
        <li class="btn">{{examData.type}}</li>
        <li class="right"><el-button icon="el-icon-a-032" style="font-size: 22px;" @click="toAnswer(examData.examCode)">{{$store.state.isPractice==true?'开始练习':'开始考试'}}</el-button></li>
      </ul>
      <ul class="info">
        <li @click="dialogVisible = true"><a href="javascript:;"><i class="iconfont icon-info"></i>考生须知</a></li>
      </ul>
    </div>
    <div class="content">
      <el-collapse v-model="activeName" >
        <el-collapse-item class="header" name="0">
          <template slot="title">
            <div class="title">
              <span>{{examData.source}}</span><i class="header-icon el-icon-a-041"></i>
              <span class="time">{{score[0]+score[1]+score[2]}}分 / {{examData.totalTime}}分钟</span>
              <el-button type="primary" size="small">点击查看试题详情</el-button>
            </div>
          </template>
          <el-collapse class="inner">
            <el-collapse-item>
              <template slot="title">
                <div class="titlei">选择题 (共{{topicCount[0]}}题 共计{{score[0]}}分)</div>
              </template>
              <div class="contenti">
                <ul class="question" v-for="(list, index) in topic[1]" :key="index">
                  <li>{{index+1}}. {{list.question}} {{list.score}}分</li>
                </ul>
              </div>
            </el-collapse-item>
            <el-collapse-item>
              <template slot="title">
                <div class="titlei">填空题 (共{{topicCount[1]}}题  共计{{score[1]}}分)</div>
              </template>
              <div class="contenti">
                <ul class="question" v-for="(list, index) in topic[2]" :key="index">
                  <li>{{topicCount[0]+index+1}}.{{list.question}}  {{list.score}}分</li>
                </ul>
              </div>
            </el-collapse-item>
            <el-collapse-item>
              <template slot="title">
                <div class="titlei">判断题 (共{{topicCount[2]}}题 共计{{score[2]}}分)</div>
              </template>
              <div class="contenti">
                <ul class="question" v-for="(list, index) in topic[3]" :key="index">
                  <li>{{topicCount[0]+topicCount[1]+index+1}}. {{list.question}} {{list.score}}分</li>
                </ul>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-collapse-item>
        
      </el-collapse>
    </div>
    <!--考生须知对话框-->
    <el-dialog
      title="考生须知"
      :visible.sync="dialogVisible"
      width="30%">
      <span>{{examData.tips}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">知道了</el-button>
      </span>
    </el-dialog>
   </div>
   
   <i class="el-icon-s-comment" style="transform: scale(2.5);"></i>
   <el-badge :value="1" class="item">
    <el-button  @click="handleButtonClick" size="small" round>
        最新学习报告
    </el-button>
  </el-badge>
    <el-drawer
    title="最新学习报!"
    :visible.sync="table"
    direction="rtl"
    size="50%">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
    <span>最新科目--{{examData.source}}--建议</span>
    <el-button style="float: right; padding: 3px 0" type="text">推荐练习</el-button>
     </div>
     <div v-for="(text, index) in kechengQK" :key="index" v-html="processText(text)" class="text item"></div>
     </el-card>
      <br>
      
       {{ paperQK }}
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false, //对话框属性
      activeName: '0',  //默认打开序号
      topicCount: [],//每种类型题目的总数
      score: [],  //每种类型分数的总数
      examData: { //考试信息
        // source: null,
        // totalScore: null,
      },
      topic: {  //试卷信息

      },
      table: false,//弹出框
      dialog: false,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '80px',
      timer: null,
      returnkechengQK:'',
      paperQK:'',
      questionValue:"",
      kechengQK: [],// 用于存储流式输出的每一行内容
    }
  },
  created() {
 // this.kechengQK = 'your initial value'; // 在created生命周期中初始化
  },
  mounted() {
    this.init()
  },
  methods: {
    processText(text) {
    // 处理文本，去除 ** 并将换行符转换为 <br> 标签
    return text.replace(/\*\*/g, '').replace(/\n/g, '<br>');
  },
    //初始化页面数据
    init() {
      let examCode = this.$route.query.examCode //获取路由传递过来的试卷编号
      this.$axios(`/api/exam/${examCode}`).then(res => {  //通过examCode请求试卷详细信息
        res.data.data.examDate = res.data.data.examDate.substr(0,10)
        this.examData = { ...res.data.data}
        let paperId = this.examData.paperId
        this.$axios(`/api/paper/${paperId}`).then(res => {  //通过paperId获取试题题目信息
          this.topic = {...res.data}
          let keys = Object.keys(this.topic) //对象转数组
          keys.forEach(e => {
            let data = this.topic[e]
            this.topicCount.push(data.length)
            let currentScore = 0
            for(let i = 0; i< data.length; i++) { //循环每种题型,计算出总分
              currentScore += data[i].score
            }
            this.score.push(currentScore) //把每种题型总分存入score
          })
        })
      })
    },
    toAnswer(id) {
      this.$router.push({path:"/answer",query:{examCode: id}})
    },
    //发送id与科目-------------------------
    handleButtonClick() {
      console.log(this.$cookies.get("cid"));
      this.table = true;// 显示表格
      // 发送数据到服务器
      this.sendDataToServerkemu();//科目请求
      console.log('第一二次'+this.returnkechengQK);
      
      //this.sendDataToServerpaper();//试卷请求-----------解开
      //console.log(this.paperQK);
      console.log("11111"+this.kechengQK);
    
    },
    //火星
    
    initUrl() {
       return new Promise((resolve, reject) => {
        // 初始化问题值为空字符串
        let questionValue = '';

        // 引入加密和 WebSocket 模块
        const crypto = require('crypto');

        // 获取当前时间的 GMT 字符串
        const dateString = new Date().toGMTString();

        // 定义星火 API 的主机和路径
        const host = 'spark-api.xf-yun.com';
        const path = '/v3.5/chat';

        // 构建用于签名的请求头
        let tmp = `host: ${host}\ndate: ${dateString}\nGET ${path} HTTP/1.1`;

        const APISecret = "YjQ1MmMxNmZhNTNjNDYxZmViODU2YjZm";  // 星火 APISecret 这里直接填入你自己的APISecret即可 格式如：ZjAafHbiODRdMjiyamM1azc3Yju1gMy1
        let signature = crypto
          .createHmac('sha256', APISecret)
          .update(tmp)
          .digest('base64');

        const APIKey = "1312f81a1b7cf9d87cc52605326be9f0";  // 星火 APIKey 这里直接填入你自己的APISecret即可 格式如：4220a1b1881d40e8d70eb23fd1225cd1
        const authorization_origin = `api_key="${APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`;

        // 将授权信息编码为 Base64 格式
        let buff = Buffer.from(authorization_origin);
        const authorization = buff.toString('base64');

        // 构建访问星火 API 的 WebSocket URL
        const signUrl = `wss://${host}${path}?authorization=${authorization}&date=${encodeURIComponent(dateString)}&host=${host}`;

        // 创建 WebSocket 连接
        let ws = new WebSocket(signUrl);
        //定义问题
        let request=this.returnkechengQK;

        // 当连接打开时发送聊天请求
        ws.onopen= function () {
          console.log('讯飞星火连接sock连接成功!!!!');
          ws.send(
            JSON.stringify({
              header: {
                app_id: "83f52498",  // 星火应用程序 ID  APPID 格式为 dbfab529
              },
              parameter: {
                chat: {
                  domain: 'generalv3.5',
                  temperature: 0.5,
                  max_tokens: 1024,
                },
              },
              payload: {
                message: {
                  text: [
                    {
                      role: 'user',
                      content: request,
                    },
                  ],
                },
              },
            })
          );
        };

        // 监听连接的错误事件
        ws.onerror= function (err) {
          console.log('error: ', err);
          reject(err);
        };

        // 在 Vue 实例外部存储 this 关键字的引用
        const self = this;
        // 监听消息事件，处理 API 响应
        ws.onmessage= function (event) {

          // 清空 kechengQK 数组
          self.kechengQK = [];

          // 解析 API 响应的 JSON 数据
          const obj = JSON.parse(event.data);
          // 提取文本消息
          const texts = obj.payload.choices.text;

          // 将文本消息拼接到问题值中
          texts.forEach((item) => {
            questionValue += item.content;
            self.kechengQK.push(questionValue);
          });
          // 更新 Vue 实例中的数据属性
          //console.log(this.kechengQK); // 打印更新后的值
        };

        // 监听连接关闭事件，将结果通过 resolve 返回
        ws.onclose= function () {
          resolve(questionValue);
        };
      });
      },
      async sendDataToServerkemu() {
        try {
       // 准备发送的数据
    const dataToSend = {
      studentId: this.$cookies.get("cid"), // 学号
      subject: this.examData.source, // 课程名称
    };// 发送 POST 请求到端口 8081
   const response = await fetch('http://localhost:8081/error-question/whole', {
      method: 'POST', // 注意这里改为 POST 请求
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(dataToSend)
    });

    // 解析服务器返回的响应数据
    const data = await response.json();

    this.returnkechengQK=data.data;
    console.log('从服务器接收到的信息：', this.returnkechengQK);
    //----------------------------------------------------------------
         this.initUrl(this.returnkechengQK).then((result) => {

            console.log('Result:', result);
            }).catch((err) => {
             console.error('Error:', err);
            });
  } catch (error) {
    // 处理错误
    console.error('发送数据时出错：', error);
  }
  },
  async sendDataToServerpaper() {
        try {
       // 准备发送的数据
      const dataToSend = {
      studentId: this.$cookies.get("cid"), // 学号
      examCode: this.$route.query.examCode, //获取路由传递过来的试卷编号,
      subject: this.examData.source, // 课程名称
    };// 发送 POST 请求到端口 8081
   const response = await fetch('http://localhost:8081/error-question/paper', {
      method: 'POST', // 注意这里改为 POST 请求
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(dataToSend)
    });

    // 解析服务器返回的响应数据
    const datapaper = await response.json();
    console.log('从服务器接收到的试卷信息：', datapaper);
    this.paperQK=datapaper.data;
  } catch (error) {
    // 处理错误
    console.error('发送数据时出错：', error);
  }
  },


}
}
</script>

<style lang="less" scoped>
.text {//卡片
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 600px;
    margin: 0 auto; /* 将卡片水平居中 */
  }

.container {
        display: flex;
        justify-content: space-between; /* 让内部元素左右对齐 */
        align-items: flex-end; /* 让按钮位于容器底部 */
    }

.bottom {
  .right{
    .el-button{
      color: #409EFF;
      border-color: #c6e2ff;
      background-color: #ecf5ff;
    }
  }
}
.right {
  margin-left: auto;
}
.inner .contenti .question {
  margin-left: 40px;
  color: #9a9a9a;
  font-size: 14px;
}
.content .inner .titlei {
  margin-left: 20px;
  font-size: 16px;
  color: #88949b;
  font-weight: bold;
}
.content .title .time {
  font-size: 16px;
  margin-left: 420px;
  color: #999;
}
.content .stitle {
  background-color: #0195ff;
}
.content .title span {
  margin-right: 10px;
}
#msg .content .title {
  font-size: 20px;
  margin: 0px;
  display: flex;
  align-items: center;
}
.content {
  margin-top: 20px;
  background-color: #fff;
}
.content .header {
  padding: 10px 30px;
}
.wrapper .info {
  margin: 20px 0px 0px 20px;
  border-top: 1px solid #eee;
  padding: 20px 0px 10px 0px;
}
.wrapper .info a {
  color: #88949b;
  font-size: 14px;
}
.wrapper .info a:hover {
  color: #0195ff;
}
.wrapper .bottom .btn {
  cursor: pointer;
  padding: 5px 10px;
  border: 1px solid #88949b;
  border-radius: 4px;
} 
.wrapper .bottom {
  display: flex;
  margin-left: 20px;
  color: #999;
  font-size: 14px;
  align-items: center;
}
.wrapper .bottom li {
  margin-right: 14px;
}
#msg {
  background-color: #eee;
  width: 980px;
  margin: 0 auto;
}
#msg .title {
  margin: 20px;
}
#msg .wrapper {
  background-color: #fff;
  padding: 10px;
}
.wrapper .top {
  display: flex;
  margin: 20px;
  align-items: center;
}
.wrapper .top .right {
  margin-left: auto;
}
.wrapper .top .example {
  color: #333;
  font-size: 22px;
  font-weight: 700;
}
.wrapper .top li i {
  margin-left: 20px;
  color: #88949b;
}
.wrapper .right .count {
  margin-right: 60px;
  color: #fff;
  padding: 4px 10px;
  background-color: #88949b;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  border: 1px solid #88949b;
}
.wrapper .right .score {
  position: absolute;
  left: 53px;
  top: -5px;
  padding: 1px 12px;
  font-size: 20px;
  color: #88949b;
  border: 1px dashed #88949b;
  border-left: none;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
  font-weight: bold;
}
.wrapper .right div {
  position: relative;
}
</style>
